//
//  ZpNetWorkTool.m
//  WeiBo_OC
//
//  Created by MacBook Pro on 16/5/28.
//  Copyright © 2016年 MacBook Pro. All rights reserved.
//

#import "ZpNetWorkTool.h"
#import "ZpNetWorkInfo.h"
@interface ZpNetWorkTool ()


@end
@implementation ZpNetWorkTool

+ (instancetype)shareNetWorkTool{
    
    static ZpNetWorkTool *tool = nil;
    static dispatch_once_t one;
    dispatch_once(&one, ^{
        tool = [[ZpNetWorkTool alloc] init];
    });

    
    return tool;
}

- (instancetype)init{
    if (self = [super init]) {
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:  [[NSBundle mainBundle]pathForResource:@"NetWorkInformation.plist" ofType:nil]];
        self.info = [ZpNetWorkInfo sharenNetWork:dict];
    }
    return self;
}


#pragma mark - 授权方法


- (void)sendHttpRequestWithMethod:(HttpMethod)method andParameters:(NSDictionary *)parameters andURLString:(NSString *)urlString andfinshed:(FinshedNetWork)finshed
{
    NSMutableString *urlStringM = [urlString mutableCopy];
    NSString *dataStr = [self dictionaryToString:parameters];
    NSMutableURLRequest *request = nil;
    if (method == POST) {
        NSURL *url = [NSURL URLWithString:urlString];
        request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        
        request.HTTPBody = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
        
    }else{
        [urlStringM appendFormat:@"%@", dataStr];
        NSLog(@"%@", urlString);
        NSURL *url = [NSURL URLWithString:urlStringM];
        request = [NSMutableURLRequest requestWithURL:url];
    }
    
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 子线程中
        // 回到主线程中做UI操作
        dispatch_async(dispatch_get_main_queue(), ^{
            finshed(data, error);
        });
    }] resume];
}

- (NSString *)dictionaryToString:(NSDictionary *)dict{
    NSMutableString *strM = [NSMutableString string];
    [dict enumerateKeysAndObjectsUsingBlock:^(NSString * key, NSString * obj, BOOL * _Nonnull stop) {
        [strM appendString:[NSString stringWithFormat:@"%@=%@&", key, obj]];
    }];
    
    return [strM substringToIndex:strM.length - 1];
}
@end
